<template>
  <div class="type-practice-page">
    <!-- 顶部导航栏 -->
    <el-header class="navbar">
      <div class="logo">思不罔学习平台</div>
      <el-menu mode="horizontal" :default-active="activeMenu" @select="handleSelect">
        <el-menu-item index="1" @click="goBackHome">首页</el-menu-item>
        <el-menu-item index="2" @click="goToPersonal">个人中心</el-menu-item>
        <el-menu-item index="3" @click="goToCollection">我的收藏</el-menu-item>
      </el-menu>
      <div class="auth-buttons">
        <el-button link @click="goToLogin">退出登录</el-button>
      </div>
    </el-header>

    <!-- 主体内容 -->
    <el-main class="practice-content">
      <h2 class="section-title">题型练习</h2>

      <el-card shadow="hover" class="beautiful-practice-card">
        <div class="practice-intro">
          <p>📚 选择学科和题型进行专项练习，提升解题能力。</p>
        </div>

        <!-- 学科选择 -->
        <div class="selection-section">
          <div class="selection-item" style="width: 300px; height: 60px;">
            <span class="selection-label">选择学科：</span>
            <el-select
                v-model="selectedMajor"
                placeholder="请选择学科"
                class="major-select"
                size="large"
                style="width: 100%"
            >
              <el-option
                  v-for="major in majors"
                  :key="major.majorId"
                  :label="major.majorName"
                  :value="major.majorId"
              />
            </el-select>
          </div>

          <!-- 题型选择 -->
          <div class="selection-item">
            <span class="selection-label">选择题型：</span>
            <el-checkbox-group v-model="selectedTypes" class="type-checkbox-group">
              <el-checkbox label="choice">选择题</el-checkbox>
              <el-checkbox label="fill_in">填空题</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>

        <el-button
            class="start-button"
            type="primary"
            @click="startPractice"
            :disabled="!canStart"
        >
          <i class="fas fa-play-circle"></i> 开始练习
        </el-button>
      </el-card>
    </el-main>

    <!-- 题目弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="题目练习"
        width="800px"
        :close-on-click-modal="false"
        :before-close="handleDialogClose"
        custom-class="custom-dialog"
    >
      <!-- 复用Order.vue的题目弹窗内容 -->
      <div v-if="currentQuestion" class="question-block">
        <div class="question-header">
          <div class="question-number">第 {{ currentQuestionIndex + 1 }} 题</div>
          <div class="question-type">
            {{ currentQuestion.questionType === 'choice' ? '选择题' : '填空题' }}
          </div>
        </div>

        <div class="question-content">
          {{ currentQuestion.content }}
        </div>

        <!-- 选择题 -->
        <div class="options-container" v-if="currentQuestion.questionType === 'choice'">
          <el-radio-group v-model="selectedAnswer" class="radio-options-group">
            <el-radio
                v-for="(option, index) in currentQuestion.questionChoicesList.slice(0, 4)"
                :key="option.choiceId"
                :label="getOptionLabel(option.choiceContent)"
            >
              {{ option.choiceContent }}
            </el-radio>
          </el-radio-group>
        </div>

        <!-- 填空题 -->
        <div class="fill_in-container" v-if="currentQuestion.questionType === 'fill_in'">
          <el-input
              v-model="selectedAnswer"
              placeholder="请输入答案。"
              clearable
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <div class="action-buttons-full">
            <div class="left-buttons">
              <el-button
                  v-if="currentQuestion"
                  link
                  class="favorite-btn"
                  @click="toggleFavorite"
                  title="收藏/取消收藏"
              >
                <svg
                      :fill="isCollected ? '#ffb600' : '#ccc'"
                      width="24"
                      height="24"
                      viewBox="0 0 24 24"
                  >
                    <path d="M12 .587l3.668 7.568 8.332 1.151-6.064 5.828 
                    1.416 8.279-7.432-3.907-7.432 3.907 1.416-8.279-6.064-5.828 
                    8.332-1.151z" 
                    stroke="none" 
                    stroke-width="0" 
                    fill-rule="evenodd"
                    transform="scale(0.9) translate(1.2, 1)"
                  />
                </svg>
              </el-button>

              <el-button @click="prevQuestion" :disabled="currentQuestionIndex === 0">
                <i class="fas fa-arrow-left"></i> 上一题
              </el-button>
              <el-button @click="nextQuestion" :disabled="currentQuestionIndex >= questions.length - 1">
                下一题 <i class="fas fa-arrow-right"></i>
              </el-button>
            </div>

            <div class="right-buttons">
              <el-button @click="dialogVisible = false">关闭</el-button>
              <el-button type="primary" @click="submitAnswer">提交答案</el-button>
            </div>

            <div class="next-page-section" style="margin-top: 20px; text-align: center">
              <el-button
                  type="success"
                  @click="nextPage"
                  :disabled="(currentPage * pageSize) >= fullQuestionList.length"
              >
                下一页题目
              </el-button>
            </div>
          </div>
        </div>

        <!-- 正确答案展示 -->
        <div v-if="showCorrectAnswer" class="correct-answer">
          <i class="fas fa-check-circle"></i> 正确答案：<strong>{{ currentQuestion.answer }}</strong>

          <!-- 总回答次数 -->
          <div class="answer-stats">
            总回答次数：<strong>{{ currentQuestion.answerTotal || 0 }}</strong>
          </div>

          <!-- 正确率 -->
          <div class="answer-stats">
            正确率：<strong>{{ currentQuestion.correctRate }}</strong>
          </div>
        </div>

        <!-- 评论区 -->
        <div class="comments-section">
          <h3><i class="fas fa-comments"></i> 题目评论</h3>

          <!-- 评论列表滚动区域 -->
          <div class="comment-list-wrapper">
            <div v-if="comments && comments.length > 0" class="comments-list">
              <div
                  v-for="(comment, idx) in comments"
                  :key="idx"
                  class="comment-item"
              >
                <div class="comment-author">
                  <i class="fas fa-user-circle"></i> {{ comment.author }}
                </div>
                <div class="comment-content">
                  {{ comment.content }}
                </div>
                <div class="comment-like">
                  <el-button
                      link
                      class="like-btn"
                      @click="toggleLike(comment)"
                      title="点赞 / 取消点赞"
                  >
                    <svg
                        width="20"
                        height="20"
                        viewBox="0 0 24 24"
                        :fill="comment.hasLiked ? '#f56c6c' : '#ccc'"
                    >
                      <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5
               2 6.01 4.01 4 6.5 4c1.74 0 3.41 1.01 4.13 2.44h1.74C14.09 5.01 15.76 4 17.5 4
               19.99 4 22 6.01 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                    </svg>
                    <span style="margin-left: 4px">{{ comment.likeCount }}</span>
                  </el-button>

                  <!-- 删除按钮（当前用户是作者或管理员才显示） -->
                  <el-button
                      v-if="comment.userId === currentUserId || isAdmin"
                      link
                      class="delete-btn"
                      @click.stop="deleteComment(comment.commentId)"
                      title="删除评论"
                  >
                    <svg
                        width="20"
                        height="20"
                        viewBox="0 0 24 24"
                        fill="#f56c6c"
                    >
                      <path d="M3 6h18v2H3V6zm2 3h14v13H5V9zm3 3v7h2v-7H8zm4 0v7h2v-7h-2zm4 0v7h2v-7h-2z"/>
                    </svg>
                    <span style="margin-left: 4px">删除</span>
                  </el-button>
                </div>
              </div>
            </div>

            <div v-else class="no-comments">
              <p>暂无评论，快来发表你的见解！</p>
            </div>
          </div>

          <!-- 输入框和按钮 -->
          <el-input
              v-model="newComment"
              placeholder="写下你的评论..."
              type="textarea"
              :rows="3"
              class="new-comment-input"
          />
          <el-button
              type="primary"
              class="submit-comment-btn"
              @click="submitComment"
          >
            <i class="fas fa-paper-plane"></i> 提交评论
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from '@/api/server';
import { useUserStore } from '../store/useUserstore';

const router = useRouter();
const activeMenu = ref('1');
const dialogVisible = ref(false);
const currentQuestionIndex = ref(0);
const selectedAnswer = ref('');
const currentQuestion = ref(null);
const showCorrectAnswer = ref(false);
const questions = ref([]);
const comments = ref([]);
const newComment = ref('');
const currentUserId = ref(null);
const isAdmin = ref(false);
const fullQuestionList = ref([]);
const pageSize = 10;
const currentPage = ref(1);
const progressCache = ref({});
const STORAGE_KEY = 'practiceProgress';

// 新增：学科和题型选择相关变量
const majors = ref([]);
const selectedMajor = ref(null);
const selectedTypes = ref(['choice', 'fill_in']); // 默认全选

const isCollected = computed(() => currentQuestion.value?.isCollected);
const canStart = computed(() => selectedMajor.value !== null && selectedTypes.value.length > 0);

// 获取学科列表
const fetchMajors = async () => {
  try {
    const res = await axios.get('/admin/manage/majors');
    majors.value = res.data.data || [];
    if (majors.value.length > 0) {
      selectedMajor.value = majors.value[0].majorId; // 默认选择第一个学科
    }
  } catch (error) {
    ElMessage.error('学科加载失败');
    console.error(error);
  }
};

onMounted(() => {
  fetchMajors();
});

const saveProgress = (cache) => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(cache));
};

const getOptionLabel = (content) => {
  return content;
};
const startPractice = async () => {
  if (!canStart.value) {
    ElMessage.warning('请选择学科和题型');
    return;
  }

  try {
    await ElMessageBox.confirm(
        '是否重新开始做题？\n选择"是"将清空之前的做题记录，选择"否"继续之前的进度。',
        '重新开始确认',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }
    );
    localStorage.removeItem(STORAGE_KEY);
    progressCache.value = {};
  } catch (e) {
    // 用户取消，保留进度
  }

  try {
    // 修改为获取所有题目数据
    const res = await axios.get('/question/list'); // 假设后端提供获取所有题目的接口

    const allData = res.data.data || [];
    if (!allData || allData.length === 0) {
      ElMessage.warning('暂无题目数据');
      return;
    }

    // 前端过滤逻辑：按学科和题型筛选
    const filteredData = allData.filter(item =>
        item.majorId === selectedMajor.value &&
        selectedTypes.value.includes(item.questionType))

    if (filteredData.length === 0) {
      ElMessage.warning('该学科和题型下暂无题目');
      return;
    }

    fullQuestionList.value = filteredData.map(q => {
      const cached = progressCache.value[q.questionId] || {};
      return {
        ...q,
        userAnswer: cached.userAnswer || '',
        hasShownAnswer: cached.hasShownAnswer || false,
      };
    });

    currentPage.value = 1;
    loadCurrentPageQuestions();
  } catch (err) {
    ElMessage.error('题目加载失败');
    console.error(err);
  }
};

const loadCurrentPageQuestions = async () => {
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  questions.value = fullQuestionList.value.slice(start, end);

  if (questions.value.length > 0) {
    currentQuestionIndex.value = 0;
    currentQuestion.value = questions.value[0];
    await loadComments();
    selectedAnswer.value = currentQuestion.value.userAnswer || '';
    showCorrectAnswer.value = currentQuestion.value.hasShownAnswer || false;
    dialogVisible.value = true;
  } else {
    ElMessage.warning('没有更多题目了');
  }
};

const submitAnswer = async () => {
  const user = selectedAnswer.value.trim();
  const question = currentQuestion.value;

  if (!user) {
    ElMessage.warning('请选择或填写答案');
    return;
  }

  question.userAnswer = user;
  question.hasShownAnswer = true;
  showCorrectAnswer.value = true;

  progressCache.value[question.questionId] = {
    ...(progressCache.value[question.questionId] || {}),
    userAnswer: user,
    hasShownAnswer: true,
    isCollected: question.isCollected || false
  };
  saveProgress(progressCache.value);

  try {
    const res = await axios.post('/question/submit', {
      questionId: question.questionId,
      submitAnswer: user
    });

    const data = res.data?.data;

    if (res.data.code !== 1 || !data) {
      ElMessage.error(res.data.msg || '提交失败');
      return;
    }

    ElMessage[data.isCorrect ? 'success' : 'error'](data.message || '');
  } catch (e) {
    ElMessage.error('提交答案失败，请稍后重试');
  }
};

const toggleFavorite = async () => {
  const question = currentQuestion.value;
  const userStore = useUserStore();

  const userInfoStr = localStorage.getItem('userInfo');
  if (userInfoStr) {
    const userInfo = JSON.parse(userInfoStr);
    userStore.setUserInfo(userInfo);
  }

  if (!question) return;

  try {
    await axios.post(`/users/favorite/${question.questionId}`);
    question.isCollected = !question.isCollected;
    ElMessage.success(question.isCollected ? '题目已收藏' : '已取消收藏');
  } catch {
    ElMessage.error('操作失败，请稍后再试');
  }
};

const nextPage = () => {
  ElMessageBox.confirm('是否继续下一页的练习？', '继续确认', {
    confirmButtonText: '继续',
    cancelButtonText: '取消',
    type: 'info',
  }).then(() => {
    currentPage.value++;
    loadCurrentPageQuestions();
  }).catch(() => {
    ElMessage.info('已取消继续练习');
  });
};

const submitComment = async () => {
  const token = localStorage.getItem('token');
  const userInfoString = localStorage.getItem('userInfo');
  const userId = userInfoString ? JSON.parse(userInfoString)?.userId : null;

  if (!token || !userId) {
    ElMessage.warning('请先登录后再评论');
    router.push('/');
    return;
  }

  if (!newComment.value.trim()) {
    ElMessage.warning('评论不能为空');
    return;
  }

  try {
    await axios.post('/users/comments/add', {
      questionId: currentQuestion.value.questionId,
      content: newComment.value.trim()
    });

    ElMessage.success('评论成功');
    newComment.value = '';
    await loadComments();
  } catch {
    ElMessage.error('评论失败');
  }
};

const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除该评论吗？', '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('请先登录');
      router.push('/');
      return;
    }

    await axios.delete(`/users/comments/delete/${commentId}`, {
      headers: { Authorization: `Bearer ${token}` }
    });

    ElMessage.success('评论删除成功');
    await loadComments();
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('评论删除失败');
    }
  }
};

const loadComments = async () => {
  const userInfoStr = localStorage.getItem('userInfo');
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr);
      currentUserId.value = userInfo.userId;
      isAdmin.value = userInfo.isAdmin || false;
    } catch {
      currentUserId.value = null;
      isAdmin.value = false;
    }
  }

  try {
    const res = await axios.get(`/users/comments/get/${currentQuestion.value.questionId}`);
    const commentList = res.data.data || [];

    let likedCommentIds = [];
    const token = localStorage.getItem('token');
    let likeCountList = [];

    if (token) {
      const likeRes = await axios.get(`/users/commentlike/list/${currentQuestion.value.questionId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      likedCommentIds = likeRes.data.data || [];
    }

    if (token) {
      try {
        const likeCountRes = await axios.get(`/users/commentlike/count/${currentQuestion.value.questionId}`, {
          headers: {
            Authorization: `Bearer ${token}`
          }
        });
        likeCountList = likeCountRes.data.data || [];
      } catch (e) {
        console.warn('获取点赞数量失败', e);
      }
    }

    // 设置每条评论的 hasLiked 和 likeCount
    for (const comment of commentList) {
      comment.hasLiked = likedCommentIds.includes(comment.commentId);
      comment.likeCount = likeCountList.find(item => item.commentId === comment.commentId)?.likeCount || 0;
    }

    comments.value = commentList;
  } catch {
    comments.value = [];
  }
};

const toggleLike = async (comment) => {
  const token = localStorage.getItem('token');
  const userInfoString = localStorage.getItem('userInfo');
  const userId = userInfoString ? JSON.parse(userInfoString)?.userId : null;

  if (!token || !userId) {
    ElMessage.warning('请先登录后再点赞');
    router.push('/');
    return;
  }

  try {
    await axios.post(`/users/commentlike/${comment.commentId}`, null, {
      headers: { Authorization: `Bearer ${token}` }
    });

    comment.hasLiked = !comment.hasLiked;
    comment.likeCount += comment.hasLiked ? 1 : -1;
    ElMessage.success(comment.hasLiked ? '点赞成功' : '取消点赞成功');
  } catch {
    ElMessage.error('操作失败，请稍后重试');
  }
};

const prevQuestion = async () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--;
    const q = questions.value[currentQuestionIndex.value];
    currentQuestion.value = q;
    selectedAnswer.value = q.userAnswer || '';
    showCorrectAnswer.value = q.hasShownAnswer || false;
    await loadComments();
  }
};

const nextQuestion = async () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++;
    const q = questions.value[currentQuestionIndex.value];
    currentQuestion.value = q;
    selectedAnswer.value = q.userAnswer || '';
    showCorrectAnswer.value = q.hasShownAnswer || false;
    await loadComments();
  }
};

const handleSelect = (index) => console.log(index);
const goBackHome = () => router.push('/home');
const goToPersonal = () => router.push('/personal');
const goToCollection = () => router.push('/collection');
const goToLogin = () => {
  localStorage.removeItem('token');
  router.push('/');
};
</script>

<style scoped>
@import "../styles/Type.css";
</style>